<?php

namespace app\admin\controller;

use app\admin\controller\auth\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Schedu extends Backend
{
    
    /**
     * Schedu模型对象
     * @var \app\admin\model\Schedu
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Schedu;
        $groupId = AuthGroup::where('name','讲解员')
            ->value('id');
        $authGroupList = AuthGroupAccess::where('group_id',$groupId)
            ->column('uid');
        $speak = DB::table('fa_admin')->whereIn('id',implode(',',$authGroupList))->column('id,nickname');
//         dump($speak);
        $this->view->assign("name", $speak);
//        $this->assign("name", $speak); //讲解员
        $this->visitime = config("visit_time");
        $this->assign("vistime",$this->visitime);

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach($this->visitime as $k=>$val){
                foreach($list as $key=>$value){
                    if($k == $value['between_time']){
                        $list[$key]['between_time'] = $val;
                    }
                }
            }
            foreach($list as $key=>$value){
                $list[$key]['name'] = Db::name('admin')->where('id',$value['user_id'])->column('nickname');
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 导入
     */
    public  function import()
    {
        $file = $this->request->request('file');
//        dd($file);
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $result = $this->importExecl($filePath);

        $this->success();
    }


    /**
     * 使用PHPEXECL导入
     *
     * @param string $file      文件地址
     * @param int    $sheet     工作表sheet(传0则获取第一个sheet)
     * @param int    $columnCnt 列数(传0则自动获取最大列)
     * @param array  $options   操作选项
     *                          array mergeCells 合并单元格数组
     *                          array formula    公式数组
     *                          array format     单元格格式数组
     *
     * @return array
     * @throws Exception
     */
    public   function importExecl($file = '', $sheet = 0, $columnCnt = 0, &$options = [])
    {
        try {
            /* 转码 */
            $file = iconv("utf-8", "gb2312", $file);

            if (empty($file) OR !file_exists($file)) {
                throw new \Exception('文件不存在!');
            }

            /** @var Xlsx $objRead */
            $objRead = IOFactory::createReader('Xlsx');

            if (!$objRead->canRead($file)) {
                /** @var Xls $objRead */
                $objRead = IOFactory::createReader('Xls');

                if (!$objRead->canRead($file)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }

            /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
            empty($options) && $objRead->setReadDataOnly(true);
            /* 建立excel对象 */
            $obj = $objRead->load($file);
            /* 获取指定的sheet表 */
            $currSheet = $obj->getSheet($sheet);

            if (isset($options['mergeCells'])) {
                /* 读取合并行列 */
                $options['mergeCells'] = $currSheet->getMergeCells();
            }

            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑，循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }

            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $data   = [];

            /* 读取内容 */
            for ($_row = 2; $_row <= $rowCnt; $_row++) {
                $isNull = true;
                for ($_column = 1; $_column <= $columnCnt; $_column++) {
                    $cellName = Coordinate::stringFromColumnIndex($_column);
                    $cellId   = $cellName . $_row;
                    $cell     = $currSheet->getCell($cellId);
                    $data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());
                    if (!empty($data[$_row][$cellName])) {
                        $isNull = false;
                    }
                }
                /* 判断是否整行数据为空，是的话删除该行数据 */
                if ($isNull) {
                    unset($data[$_row]);
                }
//                dd($data[$_row]['A']);die();
//                foreach($this->name as $k=>$value){
//                    if($value['name'] == $data[$_row]['A']){
//                        $param['user_id'] = $value['id'];
//                    }
//                }
                $param['name']       =  $data[$_row]['A'];
//                $param['password']     = md5(123456);
//                $param['venue']      =  $data[$_row]['D'];
//                $param['company']    =  $data[$_row]['E'];
//                $param['department'] =  $data[$_row]['F'];
//                $param['position_type'] =  $data[$_row]['G'];
//                $param['views'] =  $data[$_row]['H'];
//                $param['explain'] = $data[$_row]['I'] == "需要" ? 1 :0;
//                $param['day'] = $data[$_row]['J'];
//                foreach ($this->visitime as $k=>$value){
//                    if($value == $data[$_row]['K']){
//                        $param['between_time'] = $k;
//                    }
//                }
//                $param['between_day'] = $data[$_row]['L'];
//                $param['status'] = $data[$_row]['M'] == "预约中" ? 1 :5;
//                $param['note'] =  $data[$_row]['N'];
//                $param['add_time'] = time();
                \app\admin\model\Schedu::create($param);
            }
            return $data;
        } catch (\Exception $e) {
            throw $e;
        }
    }



}
